/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wanhai.itm.converter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.model.SelectItem;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.Converter;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Radiogroup;

/**
 *
 * @author m2434
 */
public class SelectedItemConverter implements Converter{
    public Object coerceToUi(Object val, Component comp, BindContext ctx){
        String varStr = (String) val;
        
        if(comp instanceof Combobox){
            List<Comboitem> comboItemList = ((Combobox) comp).getItems();
            for(Comboitem cbi : comboItemList){
                SelectItem selectItem = (SelectItem) cbi.getValue();
                if(selectItem.getValue().equals(val)){
                    return cbi;
                }
            }
        }else if(comp instanceof Radiogroup){
            List<Radio> radioList = ((Radiogroup) comp).getItems();
            for(Radio radio : radioList){
                SelectItem selectItem = (SelectItem) radio.getValue();
                if(selectItem.getValue().equals(val)){
                    return radio;
                }
            }
        }
       
        return null;
    }
     
    public Object coerceToBean(Object val, Component comp, BindContext ctx) {
        String returnValue = null;
        
        if(val != null){
            Object obj = null;
            
            if(comp instanceof Combobox){
                obj = ((Comboitem) val).getValue();
            }else if(comp instanceof Radiogroup){
                obj = ((Radio) val).getValue();
            }
            
            if(obj instanceof SelectItem){
                SelectItem selectItem = (SelectItem) obj;
                returnValue = selectItem.getValue().toString();
            }
        }
        
        return returnValue;
    }
}
